package com.spaceobj.project.service.impl;

import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spaceobj.project.mapper.SysSearchContentMapper;
import com.spaceobj.project.pojo.SysSearchContent;
import com.spaceobj.project.service.SysSearchContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author hrzhang
 */
@Service
public class SysSearchContentServiceImpl
    extends ServiceImpl<SysSearchContentMapper, SysSearchContent>
    implements SysSearchContentService {

  @Autowired private SysSearchContentMapper sysSearchContentMapper;

  @Override
  public SaResult add(SysSearchContent sysSearchContent) {

    int result = sysSearchContentMapper.insert(sysSearchContent);
    if (result == 0) {
      return SaResult.error("新增失败");
    }
    return SaResult.ok("新增成功");
  }

  @Override
  public SaResult update(SysSearchContent sysSearchContent) {
    int result = sysSearchContentMapper.updateById(sysSearchContent);
    if (result == 0) {
      return SaResult.error("修改失败");
    }
    return SaResult.ok("修改成功");
  }

  @Override
  public SaResult list(SysSearchContent sysSearchContent) {
    QueryWrapper<SysSearchContent> queryWrap = new QueryWrapper<>();
    String content = sysSearchContent.getContent();
    if (!StringUtils.isEmpty(content)) {
      queryWrap.like("content", content);
    }
    queryWrap.orderByDesc("weights");

    List<SysSearchContent> sysSearchContentList = sysSearchContentMapper.selectList(queryWrap);

    return SaResult.ok().setData(sysSearchContentList);
  }

  @Override
  public SaResult findById(long id) {
    SysSearchContent sysSearchContent = sysSearchContentMapper.selectById(id);
    return SaResult.ok().setData(sysSearchContent);
  }

  @Override
  public void addWeight(SysSearchContent sysSearchContent) {
    QueryWrapper<SysSearchContent> queryWrap = new QueryWrapper<>();
    queryWrap.eq("content",sysSearchContent.getContent());
    SysSearchContent sysSearchContentOne=sysSearchContentMapper.selectOne(queryWrap);
    if(sysSearchContentOne!=null){
      sysSearchContentOne.setWeights(sysSearchContentOne.getWeights() + 1);
      update(sysSearchContentOne);
    }
    if(!StringUtils.isEmpty(sysSearchContent.getContent())&&sysSearchContentOne==null){
      add(sysSearchContent);
    }
  }
}
